package mylab.commons.web.mvc.controller;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.google.common.collect.Lists;
import io.swagger.annotations.ApiOperation;
import mylab.base.model.dto.Result;
import mylab.base.model.entity.Entity;
import mylab.starters.mybatis.template.SuperService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.io.Serializable;
import java.util.List;

/**
 * controller~更新
 *
 * @param <K> 对应的entity的ID
 * @param <E> 对应的entity
 * @param <S> 对应的service
 * @param <D> 对应的dto
 */
public interface UpdateController<
        K extends Serializable,
        E extends Entity<K>,
        S extends SuperService<K, E>,
        D>
        extends BaseController<K, E, S> {

    @ApiOperation(value = "单体修改")
    @ApiOperationSupport(order = 21)
    @PostMapping(value = "/update")
    default Result<Boolean> updateById(@RequestBody @Validated D updateDTO) {
        E po = fromUpdateDTO(updateDTO);
        return Result.newSuccess(getService().updateById(po));
    }


    @ApiOperation(value = "全量修改所有字段", notes = "修改所有字段，没有传递的字段会被置空")
    @ApiOperationSupport(order = 22)
    @PostMapping("/update/all")
    default Result<Boolean> updateAllById(@RequestBody @Validated D updateDTO) {
        E po = fromUpdateDTO(updateDTO);
        return Result.newSuccess(getService().updateAllById(po));
    }

    @ApiOperation(value = "批量修改")
    @ApiOperationSupport(order = 23)
    @PostMapping(value = "/update/batch")
    default Result<Boolean> updateBatchById(@RequestBody @Validated List<D> updateDTOS) {
        List<E> list = Lists.newArrayList();
        updateDTOS.forEach(dto -> list.add(fromUpdateDTO(dto)));
        return Result.newSuccess(getService().updateBatchById(list));
    }


    default E fromUpdateDTO(D updateDTO) {
        return dtoToPo(updateDTO);
    }
}
